import type { DatabaseConnectionType } from '../connection.js';
import { ComponentRepository } from './ComponentRepository.js';
import { TemplateRepository } from './TemplateRepository.js';

/**
 * Repository 工厂类，管理所有数据访问层实例
 */
export class RepositoryFactory {
  private static instance: RepositoryFactory;
  private connection: DatabaseConnectionType;
  private componentRepo?: ComponentRepository;
  private templateRepo?: TemplateRepository;

  constructor(connection: DatabaseConnectionType) {
    this.connection = connection;
  }

  /**
   * 获取单例实例
   */
  static getInstance(connection?: DatabaseConnectionType): RepositoryFactory {
    if (!RepositoryFactory.instance) {
      if (!connection) {
        throw new Error('DatabaseConnection is required for first initialization');
      }
      RepositoryFactory.instance = new RepositoryFactory(connection);
    }
    return RepositoryFactory.instance;
  }

  /**
   * 获取 Component Repository
   */
  getComponentRepository(): ComponentRepository {
    if (!this.componentRepo) {
      this.componentRepo = new ComponentRepository(this.connection);
    }
    return this.componentRepo;
  }

  /**
   * 获取 Template Repository
   */
  getTemplateRepository(): TemplateRepository {
    if (!this.templateRepo) {
      this.templateRepo = new TemplateRepository(this.connection);
    }
    return this.templateRepo;
  }

  /**
   * 检查所有 Repository 的连接状态
   */
  async checkHealth(): Promise<{
    status: 'healthy' | 'unhealthy';
    repositories: {
      component: boolean;
      template: boolean;
    };
  }> {
    try {
      const componentStatus = await this.getComponentRepository().getConnectionStatus();
      const templateStatus = await this.getTemplateRepository().getConnectionStatus();

      const allHealthy = componentStatus && templateStatus;

      return {
        status: allHealthy ? 'healthy' : 'unhealthy',
        repositories: {
          component: componentStatus,
          template: templateStatus,
        },
      };
    } catch (error) {
      return {
        status: 'unhealthy',
        repositories: {
          component: false,
          template: false,
        },
      };
    }
  }

  /**
   * 重置所有 Repository 实例
   */
  reset(): void {
    this.componentRepo = undefined;
    this.templateRepo = undefined;
  }
}

// 导出 Repository 类
export { ComponentRepository } from './ComponentRepository.js';
export { TemplateRepository } from './TemplateRepository.js';
export { BaseRepository } from './BaseRepository.js';